//
//  ITScrollowTextView.m
//  InTubePro
//
//  Created by seven on 2020/6/4.
//  Copyright © 2020 seven. All rights reserved.
//

#import "ITScrollowTextView.h"
#define ITScrollowTextViewSpace 30
@interface ITScrollowTextView(){
    BaseLabel *_lbl;
    BaseLabel *_lbl2;
    
    BaseView *_contentView;
    
    CGFloat _space;
    
    CGFloat _maxWidth;
}
@end

@implementation ITScrollowTextView


- (void)initViews{
    [super initViews];
    _maxWidth = self.width;
    _contentView = [BaseView initWithFrame:self.bounds];
    [self addSubview:_contentView];
    _contentView.clipsToBounds = YES;
    _lbl = [BaseLabel initWithFrame:self.bounds];
    [_contentView addSubview:_lbl];
    
    _lbl2 = [BaseLabel initWithFrame:self.bounds];
    [_contentView addSubview:_lbl2];
    
    CAGradientLayer *layer = [CAGradientLayer gradientColorWithStartPoint:CGPointMake(0, 0) toPoint:CGPointMake(1, 0) fromColor:ColorWithHexAplha(0x07080D, 0) toColor:ColorWithHexAplha(0x07080D, 1) locations:nil];
    layer.frame = CGRectMake(self.width-20, 0, 20, self.height);
    [_contentView.layer addSublayer:layer];
    
}

- (void)setString:(NSAttributedString *)string{
    _string = string;
    [self updateString];
}


- (void)updateString{
    [self removeAnimation];
    
    _lbl.attributedText = _string;
    [_lbl fitHeight:_lbl.height];
    
    _contentView.width = MIN(_maxWidth, _lbl.width);
    
    _space = MAX(_contentView.width-_lbl.width, ITScrollowTextViewSpace);
    _lbl.left = 0;
    _lbl2.left = _lbl.right + _space;
    _lbl2.attributedText = _string;
    [_lbl2 fitHeight:_lbl2.height];
    self.hidden = _string == nil;
    self.stopAniamtion = YES;
}

- (void)goScrollAnimation{
    if (_string == nil) {
        return;
    }
    
//    if (_lbl.width < self.width) {
//        return;//不需要滚动
//    }
    
    CGFloat speed = 40;
    
    CGFloat time = _lbl.right/speed;
    
    [UIView animateWithDuration:time delay:0 options:(UIViewAnimationOptionCurveLinear) animations:^{
        _lbl2.left = 0;
        _lbl.right = -_space;
    } completion:^(BOOL finished) {
        if (finished) {
            [self changeLbl];
        }
    }];
}

- (void)changeLbl{
    [self removeAnimation];
    
    BaseLabel *tmp = _lbl;
    _lbl = _lbl2;
    _lbl2 = tmp;
    
    _lbl2.left = _lbl.right+_space;
    
    [self goScrollAnimation];
}

- (void)removeAnimation{
    [self.layer removeAllAnimations];
    [_lbl.layer removeAllAnimations];
    [_lbl2.layer removeAllAnimations];
}

- (void)setStopAniamtion:(BOOL)stopAniamtion{
    if (_stopAniamtion == stopAniamtion) {
        return;
    }
    _stopAniamtion = stopAniamtion;
    if (_stopAniamtion) {
        [self updateString];
    }else {
        [self goScrollAnimation];
    }
}

@end
